/**
 * Project: Utilities <br>
 * Package: org.leumasjaffe.util.io
 */
package org.leumasjaffe.io;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.StringTokenizer;

import org.apache.commons.io.IOUtils;

/**
 * Class org.leumasjaffe.util.io..Command in file Command.java <br>
 * 
 * @author leumasjaffe
 * @version May 6, 2013
 * Created on: May 6, 2013
 * 
 */
public final class Command {
	
	private static final Runtime rt = Runtime.getRuntime();
	
	private Command() {
		
	}
	
	/**
	 * @param command
	 */
	public static int exec(String command) {
		return exec(command, null, null);
	}
	
	/**
	 * @param cmdarray
	 */
	public static int exec(String[] cmdarray) {
		return exec(cmdarray, null, null);
	}
	
	/**
	 * @param command
	 * @param envp
	 */
	public static int exec(String command, String[] envp) {
		return exec(command, envp, null);
	}
	
	/**
	 * @param cmdarray
	 * @param envp
	 */
	public static int exec(String[] cmdarray, String[] envp) {
		return exec(cmdarray, envp, null);
	}
	
	/**
	 * @param command
	 * @param dir
	 */
	public static int exec(String command, File dir) {
		return exec(command, null, dir);
	}
	
	/**
	 * @param cmdarray
	 * @param dir
	 */
	public static int exec(String[] cmdarray, File dir) {
		return exec(cmdarray, null, dir);
	}
	
	/**
	 * @param command
	 * @param envp
	 * @param dir
	 */
	public static int exec(String command, String[] envp, File dir) {
        if (command.length() == 0)
            throw new IllegalArgumentException("Empty command");

        StringTokenizer st = new StringTokenizer(command, "(?<!\\) ");
        String[] cmdarray = new String[st.countTokens()];
        for (int i = 0; st.hasMoreTokens(); i++)
            cmdarray[i] = st.nextToken();
		return exec(cmdarray, envp, dir);
	}
	
	/**
	 * @param cmdarray
	 * @param envp
	 * @param dir
	 */
	public static int exec(String[] cmdarray, String[] envp, File dir) {
		return exec(cmdarray, envp, dir, System.out, System.err);
	}
	
	/**
	 * @param cmdarray
	 * @param envp
	 * @param dir
	 */
	public static int exec(String[] cmdarray, String[] envp, File dir, PrintStream out) {
		return exec(cmdarray, envp, dir, out, System.err);
	}
	
	/**
	 * @param cmdarray
	 * @param envp
	 * @param dir
	 */
	public static int exec(String[] cmdarray, String[] envp, File dir, PrintStream out,
			PrintStream err) {
		int output = 0;
		try {
			Process pr = rt.exec(cmdarray, envp, dir);
			try {
				output = pr.waitFor();
				if (output != 0) {
					IOUtils.copy(pr.getErrorStream(), err);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			IOUtils.copy(pr.getInputStream(), out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return output;
	}

}
